<?php

namespace App\Services;

use App\Exceptions\ApiErrorException;
use App\Models\AppTypeModel;
use App\Models\Order;
use App\Models\OrderDlzwRisk;
use App\Models\OrderLease;
use function Symfony\Component\Translation\t;

class AlipayMessageService extends AlipayBaseService
{

    const KX_SHOPPING = 1;
    const CONSUMER = 2;


    //申请待处理	PENDING
    //审批中	APPROVAL
    //提现成功	WITHDRAWAL_S
    //提现失败	WITHDRAWAL_F
    //已出账	BILLED
    //待还款	PAY_WAITING
    //还款失败	PAYMENT_F
    //已逾期	OVERDUE
    //已销户	CANCELLED
    //还款成功	PAYMENT_S
    //审批通过	AUDIT_PASS
    //审批失败	APPROVAL_F
    //已还清	PAID_OFF
    //已结清	FINISH
    const CONSUMER_FINANCE = [
        1 =>'APPROVAL_F',
        3 =>'AUDIT_PASS',
        4 =>'PENDING',
        30 =>'PAY_WAITING',
        38 =>'OVERDUE',
        39 =>'OVERDUE',
        11 =>'PAYMENT_S',
        44 =>'PAID_OFF',
        60 =>'FINISH',
    ];
    //创单成功	CREATE
    //待支付	WAIT_PAY
    //已关闭	CLOSED
    //退款中	REFUNDING
    //已退款	REFUNDED
    //已完成	FINISHED
    //支付完成	PAID
    //已发货	IN_DELIVERY
    //部分退款	REFUND_PART
    //部分退货	RETURN_PART
    //待发货	TO_SEND_GOODS
    //部分发货	PARTIAL_DELIVERY
    //已签收	SIGNED
    const ALIPAY_KX_SHOPPING_STATUS = [
        4 => 'CREATE',
        3 => 'WAIT_PAY',
        1 => 'CLOSED',
        16 => 'REFUNDED',
        60 => 'FINISHED',
        8 => 'PAID',
        20 => 'IN_DELIVERY',
        10 => 'TO_SEND_GOODS',
        30 => 'SIGNED',
    ];

    /**
     * @throws ApiErrorException
     */
    public static function sendChangeOrderMessage($order_id,$statusSource=self::KX_SHOPPING)
    {

        $order = Order::from('sp_order_2 as o')->where('o.id', $order_id)
            ->leftjoin('sp_shop_user_2 as u', 'u.member_id', 'o.seller_id')
            ->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id')
            ->leftjoin('sp_member_2 as m', 'm.id', 'o.uid')
            ->leftjoin('sp_order_return_2 as or', 'o.id', 'or.order_id')
            ->select(
                'o.id', 'o.mini_id', 'o.uid', 'o.status', 'o.rent_total', 'o.month_total', 'o.foregift', 'o.seller_id', 'o.trade_no',
                'o.realname', 'o.mobile as user_mobile', 'o.flow_id', 'o.amount', 'o.other_order_id', 'o.other_user_id', 'o.form_id',
                'o.create_time', 'o.payer_user_id', 'o.begin_time', 'o.end_time', 'o.pay_type', 'o.order_from', 'o.is_skip', 'o.financing_type', 'o.is_renewal', 'o.parent_order_no', 'o.pact_url_2', 'o.pact_url_3'
                , 'og.goods_title', 'og.lease_price', 'og.lease_set', 'og.goods_id', 'og.setmeal_id', 'og.spec_id', 'og.lease_time',
                'og.start_date', 'og.imgurl', 'og.setmeal_foregift','o.address','o.prov', 'o.city', 'o.area'
                , 'm.cert_no', 'm.user_id', 'm.cert_name', 'm.cert_no', 'm.mobile', 'm.esign_user_id', 'm.esign_seal_id'
                , 'u.shopname', 'or.logistics_no', 'u.is_guarantee', 'o.payment', 'u.guarantee_amount', 'u.guarantee_minage',
                'u.guarantee_maxage', 'u.mechanism'
            )
            ->first();
        $order = $order ? $order->toArray() : [];
        if (!$order['uid']) {
            return;
        }

        $miniId = intval($order['mini_id']);

        $order['rent_pay'] = OrderLease::where('order_id', $order['id'])->orderBy('id', 'asc')->value('rent');
        $order['overdue_amount'] = OrderLease::where('order_id', $order['id'])->orderBy('id', 'desc')->value('rent');
        $quota=0;
        $result=OrderDlzwRisk::query()->where('order_id', $order['id'])->value('result');
        if($result){
            $result=json_decode($result,true);
            $quota=$result['data']['quota_val'];
        }
        $start_time = microtime(true);
        $now = date("Y-m-d H:i:s") . sprintf(".%03d", ($start_time - (int)$start_time) * 1000);
        $material_id = 0;


        if ($statusSource == self::KX_SHOPPING){
            $status=self::ALIPAY_KX_SHOPPING_STATUS[$order['status']];
            $merchant_biz_type='KX_SHOPPING';
            $trade_no=$order['trade_no'];
            $orderInfo = [
                'first_rent' => $order['rent_pay'],
                'lease_period' => $order['begin_time'] . '至' . $order['end_time'],
                'total_rent' => $order['rent_total'],
                'lease' => $order['month_total'] . '期',
                'thaw_deposit' => 0,
                'cash_pledge' => 0,
                'payment_amount' => 0,
                'real_date' => $order['end_time'],
                'rent_due_date' => $order['end_time'],
            ];
        }else  if ($statusSource == self::CONSUMER){
            $status=self::CONSUMER_FINANCE[$order['status']];
            $merchant_biz_type='CONSUMER_FINANCE';
            $trade_no='X'.$order['trade_no'];
            $orderInfo = [
                'first_rent' => $order['rent_pay'],
                'lease_period' => $order['begin_time'] . '至' . $order['end_time'],
                'total_rent' => $order['rent_total'],
                'lease' => $order['month_total'] . '期',
                'thaw_deposit' => 0,
                'cash_pledge' => 0,
                'payment_amount' => 0,
                'time_limit' => '一个月',
                'quota'=>$quota,
                'real_date' => $order['end_time'],
                'rent_due_date' => $order['end_time'],
            ];
        }
        if($status=='PAYMENT_S'||$status=='PAID_OFF'||$status=='FINISH'){
            $orderInfo['real_amonut']=$order['rent_pay'];
            $orderInfo['paid_back_amount'] =$order['rent_pay'];
            $orderInfo['real_time'] = date('Y-m-d H:i:s');
        }
        if (!$status) {
          return true;
        }
        if ($status=='WAIT_PAY') {
            if (!strstr($order['address'], '省') && !strstr($order['address'], '市')) {
                $address = $order['prov'] . $order['city'] . $order['area'] . $order['address'];
            } else {
                $address = $order['address'];
            }
            $merchant_biz_type='COMMUNITY_GROUP';
            $trade_no='XX'.$order['trade_no'];
            $orderInfo['address']=$address;
            $orderInfo['brand_name']='潮省心';
        }



        if ($order['status'] == 38 || $order['status'] == 39) {
            $orderInfo['overdue_amount'] = $order['overdue_amount'];
        }

        $xxz_appId=AppTypeModel::query()->where('id',$order['mini_id'])->value('app_id');


        $data = [
            "out_biz_no" => $trade_no,
            "buyer_id" => $order['user_id'],
            "order_type" => 'SERVICE_ORDER',
            "order_create_time" => date('Y-m-d H:i:s', $order['create_time']),
            "order_modified_time" => $now,
            "source_app" => 'Alipay',
            "ext_info" => [
                ['ext_key' => 'merchant_order_status', 'ext_value' => $status],
                ['ext_key' => 'merchant_biz_type', 'ext_value' => $merchant_biz_type],
                ['ext_key' => 'merchant_order_link_page', 'ext_value' => '/pages/order/order?order_id=' . $order['id']],
                ['ext_key' => 'tiny_app_id', 'ext_value' => $xxz_appId],
                [
                    'ext_key' => 'business_info', 'ext_value' => json_encode($orderInfo)
                ],
            ],// 订单扩展字段。详情可查看下文：订单扩展字段。
            "item_order_list" => [
                [
                    'item_name' => $order['goods_title'],
                    'unit_price' => $order['setmeal_foregift'],
                    'quantity' => 1,
                    'ext_info' => [['ext_key' => 'image_material_id', 'ext_value' => $material_id]],
                ]
            ],// 商品信息列表，详情可查看下文：商品信息列表。
            "amount" => $order['rent_total'],
            "pay_amount" => $order['payment'],
        ];
        if ($order['status'] == 20) {
            $data['logistics_info_list'] = ['phone_no'=>$order['user_mobile'],'logistics_code'=>'SF','tracking_no'=>$order['logistics_no']];
        }
        $request = new \AlipayMerchantOrderSyncRequest();
        $request->setBizContent(json_encode($data, JSON_UNESCAPED_UNICODE));
        $result = self::aliPayXxzRequest($miniId)->execute($request);
        self::requestLog('支付宝服务消息发送', $data, $result);
    }


    /**
     * @throws ApiErrorException
     */
    public static function sendChangeOrderLeaseMessage($order_id,$statusSource=self::KX_SHOPPING,$status='')
    {

        $order = Order::from('sp_order_2 as o')->where('o.id', $order_id)
            ->leftjoin('sp_shop_user_2 as u', 'u.member_id', 'o.seller_id')
            ->leftjoin('sp_order_goods_2 as og', 'o.id', 'og.order_id')
            ->leftjoin('sp_member_2 as m', 'm.id', 'o.uid')
            ->leftjoin('sp_order_return_2 as or', 'o.id', 'or.order_id')
            ->select(
                'o.id', 'o.mini_id', 'o.uid', 'o.status', 'o.rent_total', 'o.month_total', 'o.foregift', 'o.seller_id', 'o.trade_no', 'o.realname', 'o.mobile as user_mobile', 'o.flow_id', 'o.amount', 'o.other_order_id', 'o.other_user_id', 'o.form_id', 'o.create_time', 'o.payer_user_id', 'o.begin_time', 'o.end_time', 'o.pay_type', 'o.order_from', 'o.is_skip', 'o.financing_type', 'o.is_renewal', 'o.parent_order_no', 'o.pact_url_2', 'o.pact_url_3'
                , 'og.goods_title', 'og.lease_price', 'og.lease_set', 'og.goods_id', 'og.setmeal_id', 'og.spec_id', 'og.lease_time', 'og.start_date', 'og.imgurl', 'og.setmeal_foregift'
                , 'm.cert_no', 'm.user_id', 'm.cert_name', 'm.cert_no', 'm.mobile', 'm.esign_user_id', 'm.esign_seal_id'
                , 'u.shopname', 'or.logistics_no', 'u.is_guarantee', 'o.payment', 'u.guarantee_amount', 'u.guarantee_minage', 'u.guarantee_maxage', 'u.mechanism'
            )
            ->first();
        $order = $order ? $order->toArray() : [];
        if (!$order['uid']||empty($status)) {
            return;
        }

        $miniId = intval($order['mini_id']);

        $order['rent_pay'] =OrderLease::where('order_id', $order['id'])->orderBy('id', 'asc')->value('rent');
        $Overlease=OrderLease::where('order_id', $order['id'])->where('status',4)->orderBy('id', 'asc')->select('rent','begin_time')->first();

        $quota=0;
        $result=OrderDlzwRisk::query()->where('order_id', $order['id'])->value('result');
        if($result){
            $result=json_decode($result,true);
            $quota=$result['data']['quota_val'];
        }
        $start_time = microtime(true);
        $now = date("Y-m-d H:i:s") . sprintf(".%03d", ($start_time - (int)$start_time) * 1000);
        $material_id = 0;


        if ($statusSource == self::KX_SHOPPING){
            $merchant_biz_type='KX_SHOPPING';
            $trade_no=$order['trade_no'];
            $orderInfo = [
                'first_rent' => $order['rent_pay'],
                'lease_period' => $order['begin_time'] . '至' . $order['end_time'],
                'total_rent' => $order['rent_total'],
                'lease' => $order['month_total'] . '期',
                'thaw_deposit' => 0,
                'cash_pledge' => 0,
                'payment_amount' => 0,
                'real_date' => $order['end_time'],
                'rent_due_date' => $order['end_time'],
            ];

        }else  if ($statusSource == self::CONSUMER){
            $merchant_biz_type='CONSUMER_FINANCE';
            $trade_no='X'.$order['trade_no'];
            $orderInfo = [
                'first_rent' => $order['rent_pay'],
                'lease_period' => $order['begin_time'] . '至' . $order['end_time'],
                'total_rent' => $order['rent_total'],
                'lease' => $order['month_total'] . '期',
                'thaw_deposit' => 0,
                'cash_pledge' => 0,
                'payment_amount' => 0,
                'time_limit' => '一个月',
                'quota'=>$quota,
                'real_date' => $order['end_time'],
                'rent_due_date' => $order['end_time'],
            ];
            if($status=='PAYMENT_S'||$status=='PAID_OFF'||$status=='FINISH'){
                $orderInfo['real_amonut']=$order['rent_pay'];
                $orderInfo['paid_back_amount'] =$order['rent_pay'];
                $orderInfo['real_time'] =date('Y-m-d H:i:s');
            }
            if($status=='OVERDUE'){
                $orderInfo['overdue_amount'] = $order['rent_pay'];
                $orderInfo['account_balance'] =0;
                $orderInfo['paid_back_amount'] = $order['rent_pay'];
                $orderInfo['repayment_time'] = date('Y-m-d H:i:s',$Overlease['begin_time']?$Overlease['begin_time']:time() );
            }
            if($status=='BILLED'){
                $rent=OrderLease::where('order_id', $order['id'])->where('status',0)->orderBy('id', 'asc')->select('begin_time','rent')->first();
                $orderInfo['account_balance'] =0;
                $orderInfo['repayment_time'] = date('Y-m-d H:i:s', $rent['begin_time']);
                $orderInfo['paid_back_amount'] = $rent['rent'];

            }
            if($status=='PAY_WAITING'){
                $orderInfo['repayment_time'] = date('Y-m-d H:i:s', time());
                $orderInfo['account_balance'] =0;
                $orderInfo['paid_back_amount'] =$order['rent_pay'];
            }
        }


        if ($order['status'] == 20) {
            $orderInfo['delivery_time'] = date('Y-m-d H:i:s', time());
            $orderInfo['courier_number'] = $order['logistics_no'];
        }

        if ($order['status'] == 38 || $order['status'] == 39) {
            $orderInfo['overdue_amount'] = $Overlease['rent'];
        }

        $xxz_appId=AppTypeModel::query()->where('id',$order['mini_id'])->value('app_id');


        $data = [
            "out_biz_no" => $trade_no,
            "buyer_id" => $order['user_id'],
            "order_type" => 'SERVICE_ORDER',
            "order_create_time" => date('Y-m-d H:i:s', $order['create_time']),
            "order_modified_time" => $now,
            "source_app" => 'Alipay',
            "ext_info" => [
                ['ext_key' => 'merchant_order_status', 'ext_value' => $status],
                ['ext_key' => 'merchant_biz_type', 'ext_value' => $merchant_biz_type],
                ['ext_key' => 'merchant_order_link_page', 'ext_value' => '/pages/order/order?order_id=' . $order['id']],
                ['ext_key' => 'tiny_app_id', 'ext_value' => $xxz_appId],
                [
                    'ext_key' => 'business_info', 'ext_value' => json_encode($orderInfo)
                ],
            ],// 订单扩展字段。详情可查看下文：订单扩展字段。
            "item_order_list" => [
                [
                    'item_name' => $order['goods_title'],
                    'unit_price' => $order['setmeal_foregift'],
                    'quantity' => 1,
                    'ext_info' => [['ext_key' => 'image_material_id', 'ext_value' => $material_id]],
                ]
            ],// 商品信息列表，详情可查看下文：商品信息列表。
            "amount" => $order['rent_total'],
            "pay_amount" => $order['payment'],
        ];
        $request = new \AlipayMerchantOrderSyncRequest();
        $request->setBizContent(json_encode($data, JSON_UNESCAPED_UNICODE));
        $result = self::aliPayXxzRequest($miniId)->execute($request);
        self::requestLog('支付宝服务消息发送', $data, $result);
    }

}
